<?php

include_once ('cometchat_init.php');
if (!empty($_POST['status']))
{
    $message = $_POST['status'];
    $db->query("INSERT INTO cometchat_status (userid, status) VALUES (%1, %2) ON DUPLICATE KEY UPDATE status = %2", $uid, sanitize($message));
    if ($message == 'offline')
    {
        $_SESSION['cometchat_sessionvars']['buddylist'] = 0;
    }
    echo "1";
    exit(0);
}
if (!empty($_POST['statusmessage']))
{
    $message = $_POST['statusmessage'];
    $db->query("INSERT INTO cometchat_status (userid, message) VALUES (%1, %2) ON DUPLICATE KEY UPDATE message = %2", $uid, sanitize($message));
    echo "1";
    exit(0);
}
if (!empty($_POST['to']) && !empty($_POST['message']))
{
    $to = $_POST['to'];
    $message = $_POST['message'];
    if ($uid != '')
    {
        $db->insertRow('cometchat', array('from' => $uid, 'to' => $to, 'message' => sanitize($message), 'sent' => getTime(), 'read' => 0));
        if (empty($_SESSION['cometchat_user_' . $to]))
        {
            $_SESSION['cometchat_user_' . $to] = array();
        }
        $_SESSION['cometchat_user_' . $to][] = array("id" => mysql_insert_id(), "from" => $to, "message" => sanitize($message), "self" => 1, "old" => 1);
        echo $db->insertId();
        exit(0);
    }
}
function sanitize($text)
{
    global $smileys;
    $text = htmlspecialchars($text, ENT_NOQUOTES);
    $text = str_replace("\n\r", "\n", $text);
    $text = str_replace("\r\n", "\n", $text);
    $text = str_replace("\n", "<br>", $text);
    if (DISABLE_SMILEYS != 1)
    {
        foreach ($smileys as $pattern => $result)
        {
            $text = str_ireplace($pattern, '<img class="chat_smiley" src="' . APP_URL . '/images/smileys/' . $result . '.png" alt="' . $pattern . '">', $text);
        }
    }
    return $text;
}
